package com.gwz.shelf.config;

import com.alibaba.fastjson.JSON;
import com.gwz.shelf.annotations.IgnoreResultAdvice;
import com.gwz.shelf.entity.base.IgnoreInterceptor;
import com.gwz.shelf.entity.base.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 处理解析 {@link ResponseBodyAdvice} 统一返回包装器
 */
@RestControllerAdvice(basePackages = "com.gwz.shelf.controller")
@Component
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {





    @Override
    public boolean supports(MethodParameter methodParameter,
                            Class<? extends HttpMessageConverter<?>> aClass) {
        return filter(methodParameter);
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        // o is null -> return response
        if (o == null) {
            return Result.success();
        }
        // o is instanceof ConmmonResponse -> return o
        if (o instanceof Result) {
            return o;
        }
        // string 特殊处理
        if (o instanceof String) {
            return JSON.toJSONString(Result.success(o.toString()));
        }
        return Result.success("成功", o);
    }

    private Boolean filter(MethodParameter methodParameter) {
        // 判断是否过滤,都需要过滤
        if (methodParameter.getMethodAnnotation(IgnoreResultAdvice.class) != null) {
            return false;
        }
        if (methodParameter.getMethod().getDeclaringClass().getAnnotation(IgnoreResultAdvice.class) != null) {
            return false;
        }
        return true;
    }

}